/**
 * 
 */
package com.example.radioclub.login;

import org.json.JSONException;
import org.json.JSONObject;

import com.example.radioclub.data.Constants;
import com.example.radioclub.interfaces.http.IHttpJSONDownloader;
import com.example.radioclub.tasks.http.HttpJSONDownloader;
import com.facebook.Request;
import com.facebook.Request.GraphUserCallback;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.Session.OpenRequest;
import com.facebook.Session.StatusCallback;
import com.facebook.model.GraphUser;
import com.facebook.SessionState;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

/**
 * This class wraps logging in by using Facebook account.
 * 
 * @author wizard
 * 
 */
public class FacebookLoginActivity extends Activity implements IHttpJSONDownloader {
	private final String TAG = Constants.APP_TAG + getClass().getName();
	private final String appId = Constants.FACEBOOK_APP_ID;
	private final int facebookLogin = Constants.FACEBOOK_LOGIN;

	private Session session = null;
	private OpenRequest openRequest = null;
	private StatusCallback statusCallback = null;
	private Bundle sessionBundle = null;
	private ProgressDialog progressDialog = null;
	private HttpJSONDownloader jsonDownloader;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		Log.i(TAG, "FacebookLoginActivity");
		
		AccountManager accountManager = AccountManager.get(this);
		Account[] accounts = accountManager.getAccountsByType("com.facebook");
		if(accounts.length > 0) {
			Log.i(TAG, "Internal Facebook accounts");
			for(int i=0; i<accounts.length; ++i) {
				Log.i(TAG, accounts[i].name);
			}			
		} else {
			Log.i(TAG, "No internal Facebook accounts found.");
		}

		this.statusCallback = new StatusCallback() {

			@Override
			public void call(Session session, SessionState state,
					Exception exception) {
				// TODO Auto-generated method stub
				Request.executeMeRequestAsync(session, new GraphUserCallback() {

					@Override
					public void onCompleted(GraphUser user, Response response) {
						// TODO Auto-generated method stub
						if (user != null) {
							// Log.i(TAG, "Facebook login has succeeded.");
							Constants.SOCMED_LOGIN_STATUS = true;
							if (sessionBundle == null) {
								sessionBundle = new Bundle();
								Toast.makeText(FacebookLoginActivity.this, user.getName() + " with ID = " + user.getId() + " has succesfully logged in with Facebook.", Toast.LENGTH_SHORT).show();
								Log.i(TAG, user.getName() + " with ID = " + user.getId() + " has succesfully logged in with Facebook.");
							}
							Session.saveSession(FacebookLoginActivity.this.session, sessionBundle);
							sessionBundle.putInt("login", Constants.FACEBOOK_LOGIN);
							sessionBundle.putString("id", user.getId());
							sessionBundle.putString("name", user.getName());
							sessionBundle.putString("email", user.getName().toLowerCase() + "@facebook.com");
							setResult(RESULT_OK, new Intent().putExtras(sessionBundle));
						} else {
							setResult(RESULT_CANCELED, null);
							Log.i(TAG, "User not found.");
						}
						FacebookLoginActivity.this.finish();
					}
				});
			}
		};

		if(Constants.SOCMED_LOGIN_STATUS == false) {
			this.session = new Session.Builder(this).setApplicationId(this.appId).build();
			this.session.addCallback(this.statusCallback);
			Session.setActiveSession(this.session);
			this.openRequest = new OpenRequest(this);
			this.openRequest.setCallback(this.statusCallback);
			this.session.openForRead(this.openRequest);	
		} else {
			this.setResult(RESULT_OK, null);
			this.finish();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		Log.i(TAG, "onActivityResult");
		// super.onActivityResult(requestCode, resultCode, data);
		Session.getActiveSession().onActivityResult(FacebookLoginActivity.this, requestCode, resultCode, data);
	}

	@Override
	public void onJSONDownloadFinished(String result) {
		// TODO Auto-generated method stub
		if (this.progressDialog.isShowing())
			this.progressDialog.dismiss();
		if (result == null) {
			return;
		}
		try {
			JSONObject jsonObject = new JSONObject(result);
			String profilePictureURL = jsonObject.getJSONObject("picture").getJSONObject("data").getString("url");
			this.sessionBundle.putString("picture", profilePictureURL);
			Intent data = new Intent();
			data.putExtras(this.sessionBundle);
			setResult(RESULT_OK, data);
			Log.i(TAG, "End of FacebookLoginActivity");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			Log.i(TAG, e.getMessage());
			e.printStackTrace();
		}
		this.finish();
	}
}
